import 'package:path_provider/path_provider.dart';
import 'dart:io';

import 'log_util.dart';

class FileUtils {
  static Future<String> loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(tempDir);
    if (value == 0) {
      return '0.0M';
    }
    return formatSize(value);
  }

  static Future<double> _getTotalSizeOfFilesInDir(
      final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity>? children = file.listSync();
      double total = 0;
      if (children != null)
        for (final FileSystemEntity child in children) {
          total += await _getTotalSizeOfFilesInDir(child);
        }
      return total;
    }
    return 0;
  }

  static String formatSize(double? value) {
    if (null == value) {
      return '0';
    }
    List<String> tempList = [];
    List<String> unitArr = tempList..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value! > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  static Future<bool> deleteFileData() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      await delDir(tempDir);
      return true;
    } catch (err) {
      LogUtil.e(msg: err);
      return false;
    }
  }

  static Future<void> delDir(FileSystemEntity file) async {
    if (file is File) {
      await file.delete();
      return;
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      if (children.isEmpty) {
        await file.delete();
        return;
      }
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
  }
}
